﻿using System;
using HK.Core.Common;
using HK.Core.Settings;
using HK.Editor.Defines;
using HK.Editor.Utils;
using UnityEditor;

namespace HK.Editor.BuildSystem 
{
	
	public enum BuildMode
	{
		/// <summary>
		/// Debug
		/// </summary>
		Debug = 0,
        
		/// <summary>
		/// Debug调试版
		/// </summary>
		DebugTest = 1,
        
		/// <summary>
		/// Release
		/// </summary>
		Release = 2
	}

	/// <summary>
	/// CI 模式
	/// </summary>
	public enum CiMode
	{
		/// <summary>
		/// 无
		/// </summary>
		None,
		
		/// <summary>
		/// 脚本启动
		/// </summary>
		Scripts,
		
		/// <summary>
		/// Teamcity
		/// </summary>
		TeamCity,
		
		/// <summary>
		/// Jenkins
		/// </summary>
		Jenkins
	}

	/// <summary>
	/// Build Options.
	/// </summary>
	public static class BuildParameters  {

		/// <summary>
		/// 输出目录(格式：-output [dir]).
		/// </summary>
		public static string OutputDir {
			get
			{
				string dir = null;
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return null;
				}
				for(var idx = 0; idx < args.Length; idx++)
				{
					if(args[idx] == "-output" && args.Length > idx + 1)
					{
						dir = args[idx + 1];
						break;
					}
				}
				return dir;
			}
		}
		
		/// <summary>
		/// Build ID(格式：-buildId [ID]).
		/// </summary>
		public static string BuildId {
			get
			{ 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return null;
				}
				for(var idx = 0; idx < args.Length; idx++)
				{
					if(args[idx] == "-buildId" && args.Length > idx + 1)
					{
						return args[idx + 1];
					}
				}
				return null;
			}
		}

		/// <summary>
		/// 打包No
		/// <para>* 标定打包次数的No</para>
		/// <para>* 可用以标定热更的版本或者No</para>
		/// </summary>
		public static int BuildNo
		{
			get
			{ 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return -1;
				}
				for(var idx = 0; idx < args.Length; idx++)
				{
					if(args[idx] == "-buildNo" && args.Length > idx + 1)
					{
						var argTxt = args[idx + 1];
						if (string.IsNullOrEmpty(argTxt))
						{
							return -1;
						}
						return Convert.ToInt32(argTxt);
					}
				}
				return -1;
			}
		}
		
		/// <summary>
		/// build Mode(格式：-test/-debug/-release/-production).
		/// </summary>
		public static BuildMode BuildMode 
		{
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return BuildMode.Debug;
				}
				foreach (var t in args)
				{
					if ("-test".Equals (t)) {
						return BuildMode.DebugTest;
					}
					
					if ("-debug".Equals (t)) {
						return BuildMode.Debug;
					}

					if ("-release".Equals (t)) {
						return BuildMode.Release;
					}
				}
				return BuildMode.Debug;
			}
		}

		/// <summary>
		/// 平台/渠道类型(格式：-iOS/-android/-huawei/-bilibili/-taptap/-ps4/-ps5/-pc/-pc64/-xbox).
		/// </summary>
		public static PlatformType Platform
		{
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return PlatformType.None;
				}
				foreach (var t in args)
				{
					if ("-iOS".Equals (t)) {
						return PlatformType.IOS;
					}
					
					if ("-android".Equals (t)) {
						return PlatformType.Android;
					}

					if ("-huawei".Equals (t)) {
						return PlatformType.Huawei;
					}

					if ("-bilibili".Equals (t)) {
						return PlatformType.Bilibili;
					}

					if ("-taptap".Equals (t)) {
						return PlatformType.Tabtap;
					}

					if ("-ps4".Equals (t)) {
						return PlatformType.Ps4;
					}

					if ("-ps5".Equals (t)) {
						return PlatformType.Ps5;
					}

					if ("-pc".Equals (t)) {
						return PlatformType.StandaloneWindows;
					}

					if ("-pc64".Equals (t)) {
						return PlatformType.StandaloneWindows64;
					}

					if ("-xbox".Equals (t)) {
						return PlatformType.XboxOne;
					}
				}
				return PlatformType.None;
			}
		}

		/// <summary>
		/// 是否在CI打包编译(格式：-scripts/-teamCity/-jenkins).
		/// </summary>
		public static CiMode CiMode {
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return CiMode.None;
				}

				var ciMode = CiMode.None;
				foreach (var t in args)
				{
					if(t == "-scripts")
					{
						ciMode = CiMode.Scripts;
						break;
					}
					
					if(t == "-teamCity")
					{
						ciMode = CiMode.TeamCity;
						break;
					}
					
					if(t == "-jenkins")
					{
						ciMode = CiMode.Jenkins;
						break;
					}
				}
				return ciMode;
			}
		}		
		
		/// <summary>
		/// Ab打包标识位(格式：-abBuild).
		/// </summary>
		public static bool IsAbBuild {
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return false;
				}
				foreach (var t in args)
				{
					if(t == "-abBuild")
					{
						return true;
					}
				}
				return false;
			}
		}
		
		/// <summary>
		/// Ab增量打包标识位(格式：-abDiffBuild).
		/// </summary>
		public static bool IsAbDiffBuild {
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return false;
				}
				foreach (var t in args)
				{
					if(t == "-abDiffBuild")
					{
						return true;
					}
				}
				return false;
			}
		}
			
		/// <summary>
		/// 是否为Cheat模式（可以输入命令行）(格式：-cheat).
		/// </summary>
		public static bool IsCheatMode {
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return false;
				}
				foreach (var t in args)
				{
					if(t == "-cheat")
					{
						return true;
					}
				}
				return false;
			}
		}

		/// <summary>
		/// Team Id
		/// <para>* iOS专用：与iOS开发者证书相关</para>
		/// </summary>
		public static string TeamId
		{
			get
			{
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return null;
				}
				for(var idx = 0; idx < args.Length; idx++)
				{
					if(args[idx] == "-teamId" && args.Length > idx + 1)
					{
						return args[idx + 1];
					}
				}
				return null;
			}
		}
		
		/// <summary>
		/// App版本号
		/// <para>* 例如：0.1.0</para>
		/// <para>* 注意：苹果审核版本最长3位</para>
		/// </summary>
		public static string AppVersion
		{
			get
			{
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return null;
				}
				for(var idx = 0; idx < args.Length; idx++)
				{
					if(args[idx] == "-appVer" && args.Length > idx + 1)
					{
						return args[idx + 1];
					}
				}
				return null;
			}
		}

		/// <summary>
		/// 分支名
		/// <para>* Git的分支名</para>
		/// </summary>
		public static string Branch
		{
			get
			{
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return null;
				}
				for(var idx = 0; idx < args.Length; idx++)
				{
					if(args[idx] == "-branch" && args.Length > idx + 1)
					{
						return args[idx + 1];
					}
				}
				return null;
			}
		}

		/// <summary>
		/// 加密标识位(格式：-encryption).
		/// </summary>
		public static bool Encryption
		{
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return false;
				}
				foreach (var t in args)
				{
					if(t == "-encryption")
					{
						return true;
					}
				}
				return false;
			}
		}

		/// <summary>
		/// 目标标识位(格式：-originPackage).
		/// <para>* 表示着当前打的Ab包是否为母包</para>
		/// </summary>
		public static bool OriginPackage
		{
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 0) {
					return false;
				}
				foreach (var t in args)
				{
					if(t == "-originPackage")
					{
						return true;
					}
				}
				return false;
			}
		}
		
		/// <summary>
		/// build Mode(格式：-define [agr2;arg2;arg3,...]).
		/// </summary>
		public static string[] Defines {
			get { 
				var args = Environment.GetCommandLineArgs();
				if (args.Length <= 2) {
					return null;
				}
				for(var idx = 0; idx < args.Length; idx++)
				{
					if ("-defines".Equals(args[idx]) != true || args.Length < idx + 2) continue;
					var temp = args [idx + 1];
					if(string.IsNullOrEmpty(temp)) break;
					if (temp.StartsWith("\""))
					{
						temp = temp.Substring(1);
					}
					if (temp.EndsWith("\""))
					{
						temp = temp.Substring(0, temp.Length - 1);
					}
					return temp.Split(';');
				}
				return null;
			}
		}
		
#region BuildParameters

		/// <summary>
		/// 应用参数
		/// </summary>
		public static void Apply()
		{
			if(CiMode.None == CiMode) return;
			
			// 宏
			var platformType = Platform;
			switch (platformType)
			{
				case PlatformType.Android:
				case PlatformType.Huawei:
				case PlatformType.Bilibili:
				case PlatformType.Tabtap:
					DefinesSetting.AddAndroidDefines();
					break;
				case PlatformType.IOS:
					DefinesSetting.AddIOSDefines();
					break;
				case PlatformType.StandaloneWindows:
				case PlatformType.StandaloneWindows64:
					DefinesSetting.AddPcDefines();
					break;
				case PlatformType.Ps4:
					DefinesSetting.AddPs4Defines();
					break;
				case PlatformType.Ps5:
					DefinesSetting.AddPs5Defines();
					break;
				case PlatformType.XboxOne:
					DefinesSetting.AddXboxOneDefines();
					break;
					
			}

			var isAbBuild = IsAbBuild;
			// 打包模式设定
			var buildMode = BuildMode;
			ApplyBuildMode(buildMode);

			var buildId = BuildId;
			if (!string.IsNullOrEmpty(buildId) && !isAbBuild)
			{
				PlayerSettings.applicationIdentifier = buildId;
			}
			
			// App版本号
			var appVer = AppVersion;
			if (!string.IsNullOrEmpty(appVer) && !isAbBuild)
			{
				PlayerSettings.bundleVersion = appVer;
			}

#if UNITY_IOS

			// 非Ab打包
			if (!isAbBuild)
			{
				// SDK Version - 真机包
				PlayerSettings.iOS.sdkVersion = iOSSdkVersion.DeviceSDK;
				PlayerSettings.iOS.buildNumber = $"{BuildNo}";
			
				// TeamID
				var teamId = TeamId;
				if (!string.IsNullOrEmpty(teamId))
				{
					PlayerSettings.iOS.appleDeveloperTeamID = teamId;
					//Debug.LogErrorFormat("TeamID:{0}", teamId);
				}
			}
#endif
			// 加密标志位
			var gameSettings = GameSettings.Instance;
			if (null != gameSettings)
			{
				gameSettings.Encryption = Encryption;
				UtilsSEAssets.SetAssetDirty(gameSettings);
				UtilsSEAssets.AssetsRefresh();
			}
		}

		/// <summary>
		/// 应用打包模式
		/// </summary>
		/// <param name="iMode">打包模式</param>
		private static void ApplyBuildMode(BuildMode iMode)
		{
			switch (iMode)
			{
				case BuildMode.Debug:
				{
					EditorUserBuildSettings.development = true;
				}
					break;
				case BuildMode.DebugTest:
				{
					EditorUserBuildSettings.development = true;
					EditorUserBuildSettings.connectProfiler = true;
					EditorUserBuildSettings.allowDebugging = true;
				}
					break;
				case BuildMode.Release:
				{
					EditorUserBuildSettings.development = false;
				}
					break;
			}
			
			
		}
		
#endregion

	}
}